
import { authProvider } from "./AuthProvider"



export const dataProvider = {
   

    async pushContactLog(param,callback) {
        const request = new Request(import.meta.env.VITE_BACK_SERVER_URL + import.meta.env.VITE_PUSH_CONTACT_EVENT_API_URI
            , {
                method: 'POST',
                body:JSON.stringify(param),
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    'Accept': 'application/json',
                    'token': localStorage.getItem('auth')
                },
    
            });
        let response;
    
        fetch(request).then(res => res.json()).then(res=>{
            callback(res)
    });
    },

    async pushContactRanking(param,callback) {
        const request = new Request(import.meta.env.VITE_BACK_SERVER_URL + import.meta.env.VITE_PUSH_CONTACT_RANKING_API_URI
            , {
                method: 'POST',
                body:JSON.stringify(param),
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    'Accept': 'application/json',
                    'token': localStorage.getItem('auth')
                },
    
            });
        let response;
    
        fetch(request).then(res => res.json()).then(res=>{
            callback(res)
    });
    },


    getContactEventDropdown(getPending,callback) {
        const request = new Request(import.meta.env.VITE_BACK_SERVER_URL + import.meta.env.VITE_GET_DROPDOWN_CONTACT_EVENT_API_URI
            , {
                method: 'POST',
                body:JSON.stringify({'getPending':getPending}),
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    'Accept': 'application/json',
                    'token': localStorage.getItem('auth')
                },
    
            });
        let response;
    
        fetch(request).then(res => res.json()).then(res=>{
            callback(res)
    });
    },


    deleteMany(uri,params,callback){
        const request = new Request(import.meta.env.VITE_BACK_SERVER_URL + uri
            , {
                method: 'POST',
                body:JSON.stringify(params),
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    'Accept': 'application/json',
                    'token': localStorage.getItem('auth')
                },
    
            });
        let response;
    
        fetch(request).then(res => res.json()).then(res=>{
            callback(res)
    });
    },
    async createContactEvent(eventData,callback) {
        if(eventData == null){
            console.warn("Data is empty");
            return;
        }
        eventData.createBy = (await authProvider.getIdentity()).fullName
       
        const request = new Request(import.meta.env.VITE_BACK_SERVER_URL + import.meta.env.VITE_CREATE_CONTACT_EVENT_API_URI
            , {
                method: 'POST',
                body: JSON.stringify(eventData),
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    'Accept': 'application/json',
                    'token': localStorage.getItem('auth')
                },

            });

        let callbackParam = {};
        let response;

        try {
            response = await fetch(request);
        } catch (_error) {
            authProvider.checkError(_error, response.status);
            callbackParam = {succeed:false,msg:_error};
        }
        if (response.status < 200 || response.status >= 300) {
            throw new Error(response.statusText);
        }
        const responseJson =  await response.json();
        callbackParam = {succeed:true,msg:responseJson};
        if(callback){
            callback(callbackParam);
        }
    },

    async getList(url, options) {

        const postBody = JSON.stringify({
            'filter': options.filter,
            'pagination': options.pagination,
            'sort': options.sort
        });
        const request = new Request(import.meta.env.VITE_BACK_SERVER_URL + url
            , {
                method: 'POST',
                body: postBody,
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    'Accept': 'application/json',
                    'token': localStorage.getItem('auth')
                },

            });
        let response;

        try {
            response = await fetch(request);
        } catch (_error) {
            authProvider.checkError(_error, response.status);
        }
        if (response.status < 200 || response.status >= 300) {
            throw new Error(response.statusText);
        }
        return await response.json();
    },


};


export const fileUploadProvider = {
    async uploadFile(data, param,callback) {
        const { rawFile,src, title } = data;
        let isSucceed = false;
        if (src == null || title == null) {
            return;
        }

        const formData = new FormData();
        formData.append('uploadFile', rawFile); // 'file' 是你服务器端期望的字段名
        if(param){
            formData.append('uploadParams', JSON.stringify(param));
        }

        try {
            const response = await fetch('https://wow.z-lang.top:7780/alfa/upload', {
                method: 'POST',
                body: formData,
                headers: {
                    'token': localStorage.getItem('auth')
                },
            });

            if (!response.ok) {
                throw new Error('Network response was not ok ' + response.statusText);
            }
            
            const result = await response.json(); // 解析返回的JSON数据（如果有的话）
            console.log(result); // 处理结果，例如显示成功消息或处理错误等
            isSucceed = true;
        } catch (error) {
            console.error('Error uploading file:', error);
            isSucceed = false;
        }
        if(callback){
            callback(isSucceed);
        }

    },

}
